#include "Base/ThreadTask.h"
#include "Base/Log/LogDefine.h"
#include "Base/CommonFunction.h"

CThreadTask::CThreadTask()
{
	mTickIntervalTime = 0;
	mLastTickTimestamp = getMTimestamp();
}


CThreadTask::~CThreadTask()
{
}

void CThreadTask::run(std::function<void(void)> func)
{
	bindFunction(func);

	mThreadID = self_thread_create(CThreadTask::executeThread, this);
}

void CThreadTask::tick()
{
	mTaskStatus = LOOPING;

	while (true)
	{
		unsigned long long currentMTimestamp = getMTimestamp();
		if (currentMTimestamp - mLastTickTimestamp < mTickIntervalTime)
		{
			MoheSleep(mTickIntervalTime - (currentMTimestamp - mLastTickTimestamp));
		}
	
		int i = 0;
		mLastTickTimestamp = getMTimestamp();

		mFunction();
	}
}
	

bool CThreadTask::bindFunction(std::function<void(void)> func)
{
	mFunction = func;
	return true;
}

unsigned int SELF_STDCALL CThreadTask::executeThread(void *arg)
{
	if (arg == nullptr)
	{
		LOGE("on thread call, arg is null");
		return 0;
	}
	
	LOGI("thread task starting");

	CThreadTask *t = static_cast<CThreadTask*>(arg);
	t->setTaskStatus(STARTING);

	t->tick();

	return 0;
}